package com.rp.zuul.config;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * swagger 网关配置
 * @author 笛安
 */

@Component
@Primary
@Slf4j
public class SwaggerResourceConfig1 implements SwaggerResourcesProvider {
    @Autowired
    RouteLocator routeLocator;

    //    @Value("#{${swagger.server-list}}")
    //    private Map<String, String> serverMap;

//    @Resource
//    private SwaggerConfig swaggerConfig;

    @Override
    public List<SwaggerResource> get() {
        //获取所有router
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        log.info("==========>{}", JSON.toJSONString(routes));
        log.info("Route Size:{}", routes.size());
        for (Route route : routes) {
//            String name = swaggerConfig.getServerMap().get(route.getId());
//            if (!StringUtils.isEmpty(name)) {
//                name = new String(name.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
//            } else {
//                name = route.getId();
//            }
            if (route.getFullPath().contains("-service")) {
                log.info("{}----------------------------{}",route.getId(),route.getFullPath());
                resources.add(
                        swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")));
            }        }
        return resources;
    }


    private SwaggerResource swaggerResource(String name, String location) {
        log.info("name:{},location:{}", name, location);
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}